package com.ease.archiecture.springjdbc;


import com.ease.archiecture.springjdbc.entity.TestUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class UserJdbcDao {


    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public UserJdbcDao(@Qualifier("mysqlJdbcTemplate") JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int createUser(String id, int age, String name) {
        return jdbcTemplate.update("insert into test1(ID, AGE,NAME) values(?,?, ?)", id, age, name);
    }


    public Integer userCount() {
        return jdbcTemplate.queryForObject("select count(1) from test1", Integer.class);
    }


    public TestUser findUserById(String id) {
        return jdbcTemplate.queryForObject("select * from test1 where id=" + id, new RowMapper<TestUser>() {
            @Override
            public TestUser mapRow(ResultSet resultSet, int i) throws SQLException {
                TestUser testUser = new TestUser();
                testUser.setId(resultSet.getString(1));
                testUser.setAge(resultSet.getInt(3));
                testUser.setName(resultSet.getString(2));
                return testUser;
            }
        });
    }
}
